package com.yswee.mallnavi.activity.common;

import android.os.Bundle;
import android.os.Handler;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;

import androidx.annotation.NonNull;
import androidx.viewpager.widget.PagerAdapter;
import androidx.viewpager.widget.ViewPager;

import com.yswee.framework.data.BaseArrayData;
import com.yswee.framework.data.parser.IParser;
import com.yswee.framework.manager.WindowManager;
import com.yswee.framework.net.http.Callback;
import com.yswee.framework.net.http.Entity;
import com.yswee.framework.utils.StringUtils;
import com.yswee.framework.utils.ViewInject;
import com.yswee.framework.widget.MToast;
import com.yswee.framework.widget.switchtab.SwitchDotBar;
import com.yswee.mallnavi.R;
import com.yswee.mallnavi.activity.MainActivity;
import com.yswee.mallnavi.activity.base.LoadingActivity;
import com.yswee.mallnavi.entity.Account;
import com.yswee.mallnavi.entity.common.AdsEntity;
import com.yswee.mallnavi.model.common.CommonModel;
import com.yswee.mallnavi.view.screensaver.AdsItem;

import java.util.ArrayList;

public class ScreenSaverActivity extends LoadingActivity {

    protected final static int MAXVIEWPAGERITEM = 3;
    protected final static int MSGWHAT_ADS = 0;
    protected final static int MSGWHAT_DATA = 1;
    protected final static int MSGWHAT_IN_ANIM = 2;
    protected final static int MSGDELAY_DATA = 5 * 60 * 1000;
    protected final static int MSGDELAY_IN_ANIM = 30;

    @ViewInject
    private ViewPager uvcontainer;
    @ViewInject
    private SwitchDotBar uvdotbar;
    @ViewInject
    private ImageView imgin;

    private CommonModel mCommonModel;
    private ArrayList<AdsEntity> mDataArray;
    private int velocityX = 5, velocityY = 5;

    private AdsItem[] viewList;

    private Handler mHandler = new Handler() {
        public void handleMessage(android.os.Message msg) {
            switch (msg.what) {
                case MSGWHAT_DATA:
                    getAdsList();
                    break;

                case MSGWHAT_ADS:
                    int index = uvcontainer.getCurrentItem();
                    index++;
                    if (index >= mDataArray.size()) {
                        index = 0;
                    }
                    uvcontainer.setCurrentItem(index, true);
                    break;

                case MSGWHAT_IN_ANIM:
                    refreshInImage();
                    break;

                default:
                    break;
            }
        };
    };

    private PagerAdapter mPagerAdapter = new PagerAdapter() {

        @Override
        public boolean isViewFromObject(@NonNull View view, @NonNull Object object) {
            return view == object;
        }

        @Override
        public int getCount() {
            return mDataArray != null ? mDataArray.size() : 0;
        }

        @Override
        public Object instantiateItem(View container, int position) {
            if (viewList == null) {
                viewList = new AdsItem[MAXVIEWPAGERITEM];
            }
            AdsItem view = viewList[position % viewList.length];
            if (view == null) {
                view = new AdsItem(ScreenSaverActivity.this);
                viewList[position % viewList.length] = view;
            }
            if (view.getParent() == null) {
                ((ViewPager) container).addView(view);
            }
            ((ViewPager) container).requestLayout();
            view.setDataSource(mDataArray.get(position));
            view.setTag(position);
            return view;
        }

        @Override
        public void destroyItem(View container, int position, Object object) {

        }
    };

    @Override
    protected boolean getAutoLoading() {
        return true;
    }

    @Override
    protected boolean hideContentOnAction() {
        return false;
    }

    @Override
    protected boolean checkScreenSaver() {
        return false;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_screensaver);
    }

    @Override
    protected void onBindListener() {
        super.onBindListener();
        uvcontainer.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageSelected(int position) {
                try {
                    AdsItem view = viewList[position % viewList.length];
                    view.setDataSource(mDataArray.get(position));
                    uvdotbar.setDatas(mDataArray.size(), position);
                } catch (Exception e) {

                }
            }

            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
            }

            @Override
            public void onPageScrollStateChanged(int state) {
                switch (state) {
                    case ViewPager.SCROLL_STATE_DRAGGING:
                        mHandler.removeCallbacksAndMessages(null);
                        break;

                    case ViewPager.SCROLL_STATE_IDLE:
                        int index = uvcontainer.getCurrentItem();
                        int delay = mDataArray.get(index).getIntervalTime();
                        mHandler.sendEmptyMessageDelayed(MSGWHAT_ADS, delay);
                        break;

                    default:
                        break;
                }
            }
        });
    }

    @Override
    protected void onApplyData() {
        super.onApplyData();
    }

    @Override
    public void onApplyLoadingData() {
        getAdsList();
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        finish();
        return super.dispatchTouchEvent(ev);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mHandler.removeCallbacksAndMessages(null);
    }

    private void getAdsList() {
        if(mCommonModel == null) {
            mCommonModel = new CommonModel(this);
        }
        gotoLoading();
        mCommonModel.getAdsList(new Callback<BaseArrayData<AdsEntity>>() {
            @Override
            public void onFinish(Entity<BaseArrayData<AdsEntity>> entity) {
                IParser<BaseArrayData<AdsEntity>> parser = entity.getParser();
                final BaseArrayData<AdsEntity> data = entity.getParsedData();
                if(parser.getIsOk() && data != null && data.getArray() != null) {
                    Account.get().screenSavers = data.getArray();
                    applyDataInfo();
                    gotoSuccessful();
                    return;
                }
                String msg = entity.getMessage();
                if(StringUtils.isEmpty(msg)) {
                    msg = getResources().getString(R.string.screensaver_fail);
                }
                MToast.showToastMessage(msg);
                gotoError();
            }

            @Override
            public void onError(Entity<BaseArrayData<AdsEntity>> entity) {
                gotoError();
                if(entity.getEntityStatus() != Entity.NETINVALID) {
                    MToast.showToastMessage(R.string.screensaver_fail);
                }
            }
        });
        mHandler.sendEmptyMessageDelayed(MSGWHAT_DATA, MSGDELAY_DATA);
    }

    private void applyDataInfo() {
        if (Account.get().screenSavers != null) {
            mDataArray = Account.get().screenSavers;
        } else {
            return;
        }
        if (mDataArray != null && mDataArray.size() > 0) {
            uvdotbar.setDatas(mDataArray.size(), 0);
            uvcontainer.setAdapter(mPagerAdapter);
            if (viewList != null && viewList.length > 0 && viewList[0] != null) {
                viewList[0].setDataSource(mDataArray.get(0));
            }
            mHandler.removeCallbacksAndMessages(null);
            int index = uvcontainer.getCurrentItem();
            int delay = mDataArray.get(index).getIntervalTime();
            mHandler.sendEmptyMessageDelayed(MSGWHAT_ADS, delay);
            mHandler.sendEmptyMessage(MSGWHAT_IN_ANIM);
        } else {
            if (mDataArray.size() <= 0) {
                startActivity(MainActivity.class);
                finish();
                return;
            }
            mHandler.removeCallbacksAndMessages(null);
        }
    }

    private void refreshInImage() {
        RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) imgin.getLayoutParams();
        int rightMargin = layoutParams.rightMargin;
        rightMargin += velocityX;
        if (rightMargin < 0) {
            velocityX *= -1;
            rightMargin += velocityX;
        } else if (rightMargin + imgin.getMeasuredWidth() >= WindowManager.get().getScreenWidth()) {
            velocityX *= -1;
            rightMargin += velocityX;
        }
        layoutParams.rightMargin = rightMargin;
        int bottomMargin = layoutParams.bottomMargin;
        bottomMargin += velocityY;
        if (bottomMargin < 0) {
            velocityY *= -1;
            bottomMargin += velocityY;
        } else if (bottomMargin + imgin.getMeasuredHeight() >= WindowManager.get().getScreenRealHeight()) {
            velocityY *= -1;
            bottomMargin += velocityY;
        }
        layoutParams.bottomMargin = bottomMargin;
        imgin.setLayoutParams(layoutParams);
        mHandler.sendEmptyMessageDelayed(MSGWHAT_IN_ANIM, MSGDELAY_IN_ANIM);
    }

}
